<template>
	<view class="page">
		<template v-if="scrollTop<=450">
			<view class="backBox" :style="{top:menuTop+'px'}">
				<view class="Vr" style="padding: 10rpx;border-radius: 100%;">
					<u-icon name='arrow-left' color='#fff' @click='$utils.back()' size='30rpx' />
				</view>
			</view>
			<view @click="changeimage" v-if="myUser.id==user_id"
				:style="{top:menuTop+'px',right:menuRight+20+'px',height:menuHeight+'px'}" class="VrBox">
				<view class="Vr" style="border-radius: 100%;padding: 10rpx;">
					<text class="icon-tupian iconfont" style="margin-right: 0;" />
				</view>
			</view>
		</template>
		<u-navbar v-else title="个人挑战" border @leftClick="$utils.back()" placeholder>
		</u-navbar>

		<view style="flex: 1;">
			<z-paging ref="paging" style="height: 100%;" :fixed="false" v-model="List" @query="query"
				:default-page-no="1" :hide-empty-view='true' :default-page-size="10" :auto="false" @scroll='scroll'>
				<view class="background">
					<image  mode="aspectFill" style="z-index:1;background: transparent;"
						:src="conquer.cover" class="masking"></image>
					<view class="masking" v-if="!loading" />
					<view class="userBox" :style="{top:menuTop+80+'px'}">
						<u-avatar mode='aspectFill' :src='user.avatar' size='100rpx' />
						<view style="width: 20rpx;"></view>
						<view style="flex: 1;">
							<u-text :lines='1' :text='user.nick_name' color='#fff' />
							<view style="height: 20rpx;"></view>
							<view style="display: flex;">
								<view>
									<u--text lines='1' color='#fff' :text='motto' />
								</view>
							</view>
						</view>
					</view>
					<view class="calendar Vr" @click='calendarShow=true'>
						<u-icon name="calendar" color="#fff" size="30rpx" label='日历' labelSize='24rpx'
							labelColor='#fff'></u-icon>
					</view>
					<view class="calendar Vr" style="left:180rpx ;" @click='jumpImage'>
						<u-icon name="grid" color="#fff" size="30rpx" label='对比' labelSize='24rpx'
							labelColor='#fff'></u-icon>
					</view>
					<view @click.stop="Followed" class="calendar Vr" style="left:320rpx;">
						<u-icon v-if="!isFollowed" color='#fff' labelColor='#fff' name="heart" size="24rpx"
							labelSize='28rpx' label='关注'></u-icon>
						<u-icon v-else color='#fff' labelColor='#fff' name="heart-fill" size="24rpx" labelSize='28rpx'
							label='取消关注'></u-icon>
					</view>
					<view style="bottom: 30rpx;
					color: #fff;
					display: flex;
					align-items: center;
						right: 40rpx;
						left: auto;" class='calendar' v-if="!loading">
						第
						<text class=" Vr">
							{{getTimeDifferenceInDays(conquer.conquer.start_at,new Date())}}
						</text>
						天
					</view>
					<view class="radius" />
				</view>
				<view class="viewWidth InfoBox">
					<view class="title">
						<u-icon name="attach" size="40rpx" labelSize='24rpx' label='目标信息'></u-icon>
					</view>
					<view class="infoContent" v-if='loading'>
						<view style="width: 50%;">
							<view class="mb20">
								<view style="height: 30rpx;width: 80%;" class="Skeleton" />
							</view>
							<view class="mb20">
								<view style="height: 30rpx;width: 80%;" class="Skeleton" />
							</view>
						</view>
						<view style="width: 50%;">
							<view class="mb20">
								<view style="height: 30rpx;width: 80%;" class="Skeleton" />
							</view>
							<view class="mb20">
								<view style="height: 30rpx;width: 80%;" class="Skeleton" />
							</view>
						</view>
					</view>
					<view class="infoContent " v-else>
						<view style="width: 50%;">
							<view class="mb20">
								<u--text lines='1' size='24rpx' :text='`减前基数：${conquer.weight}kg`' />
							</view>
							<view class="mb20">
								<u--text lines='1' size='24rpx' :text='`天数：${conquer.conquer.days}天`' />
							</view>
						</view>
						<view style="width: 50%;">
							<view class="mb20">
								<u--text lines='1' size='24rpx' :text='`目标减重：${conquer.conquer.weight}kg`' />
							</view>
							<view class="mb20">
								<u--text lines='1' size='24rpx' :text='`开始日期：${conquer.conquer.start_at}`' />
							</view>
						</view>
					</view>
				</view>

				<view class="viewWidth InfoBox ">
					<view class="title">
						<u-icon name="photo" size="40rpx" labelSize='24rpx' label='动态'></u-icon>
					</view>

					<view style="display:flex;overflow: auto;" class="viewWidth ">
						<view v-for="(item,index) in List" :key="index" class="access">
							<view class="iconBox" style="background-color: #D5F5DD;"
								v-if="item.last_different_weight>=0">
								<u-icon name='arrow-downward' labelPos='left' :label='item.last_different_weight+"kg"'
									size='24rpx' labelSize='20rpx' space='0' />
							</view>
							<view class="iconBox" style="background-color: red;" v-if="item.last_different_weight<0">
								<u-icon color='#fff' labelColor='#fff' name='arrow-upward' labelPos='left'
									:label='0-item.last_different_weight+"kg"' size='24rpx' labelSize='20rpx'
									space='0' />
							</view>
							<view style="font-size: 20rpx;">{{formatFun(item.created_at)}}</view>
						</view>

					</view>

					<active :start_at='conquer.conquer.start_at' :weight='conquer.conquer.weight' :list='List'
						:loading='Listloading' ref='active' :playIndex='playIndex' @reload='$refs.paging.reload()'
						@ListloadingChange='Listloading!=Listloading' />
				</view>
			</z-paging>
			<view class="bottom">
				<view @click="jumpActive" v-if="!isPublishedToday&&myUser.id==user_id ">
					<u-icon name='camera' color='#fff' size='60rpx' />
				</view>
				<view @click="open(7)">
					<text class="icon-shuzhuangtu iconfont" />
				</view>
			</view>
		</view>
		<root-portal>
			<u-popup :show="show" :round="10" @close="close">
				<view class="popupTitle">
					<u-icon name="close" color='#fff'></u-icon>
					<view>
						趋势图
					</view>
					<u-icon name="close" @click="show=false"></u-icon>
				</view>
				<view class="selectSwitchBox">
					<selectSwitch :switchList='["七天","三十天"]' @change='change' />
				</view>
				<view style="height: 24vh;">
					<view v-if="chartData" style="height: 400rpx;">
						<charts :ontouch="true" type="line" :opts="opts" :chartData="chartData" />
					</view>
				</view>
			</u-popup>
			<u-popup :show="calendarShow" :round="10" @close='calendarShow=false'>
				<view class="popupTitle">
					<u-icon name="close" color='#fff'></u-icon>
					<view>
						日历
					</view>
					<u-icon name="close" @click="showSelect=false"></u-icon>
				</view>
				<view style="height: 35vh;" v-if="calendarShow">
					<calendar :markDays='markDays' :disabledAfter='true' @onDayClick='onDayClick'
						@monthChange='monthChange' />
				</view>
			</u-popup>
		</root-portal>
	</view>
</template>

<script>
	import charts  from './components/qiun-data-charts/components/qiun-data-charts/qiun-data-charts'
	import selectSwitch from "./components/xuan-switch/xuan-switch.vue";
	import calendar from "./components/ren-calendar/ren-calendar.vue";
	import active from './components/active'
	export default {
		components: {
			charts,
			selectSwitch,
			calendar,
			active
		},
		data() {
			return {
				Listloading:true,
				token: uni.getStorageSync('token'),
				isPublishedToday: false,
				markDays: ["2024-08-10"],
				show: false,
				chartData: null,
				opts: {
					color: ["#1890FF", "#91CB74", "#FAC858", "#EE6666", "#73C0DE", "#3CA272", "#FC8452", "#9A60B4",
						"#ea7ccc"
					],
					padding: [15, 10, 0, 15],
					enableScroll: true,
					legend: {},
					xAxis: {
						disableGrid: true,
						scrollShow: true,
						itemCount: 4
					},
					yAxis: {
						gridType: "dash",
						dashLength: 2
					},
					extra: {
						line: {
							type: "straight",
							width: 2,
							activeType: "hollow"
						}
					}
				},
				menuRight: 0,
				myUser: uni.getStorageSync('user'),
				isFollowed: false,
				maxDate: 0,
				user_id: null,
				playIndex: 0,
				List: [],
				user: {},
				loading: true,
				conquer_id: 0,
				menuTop: 0,
				scrollTop: 0,
				user: {
					profile: {}
				},
				conquer: {},
				token: uni.getStorageSync('token'),
				calendarShow: false,
				date: null

			}
		},
		onLoad(op) {
			this.conquer_id = op.conquer_id
			this.user_id = op.id
			setTimeout(() => {
				this.maxDate = this.maxDatefun()
			}, 1000)
			this.$api.Conquer.Date.List(op.conquer_id, {
				date: this.maxDatefun(),
				user_id:this.user_id
			}).then(res => {
				this.markDays = res.data.dates
			})
			this.getDateil()
			let menuButtonInfo = uni.getMenuButtonBoundingClientRect() //可以获取小程序胶囊的位置。
			this.menuTop = menuButtonInfo.top
			this.menuRight = menuButtonInfo.width
			let res = uni.getSystemInfoSync()

		},
		methods: {
			jumpActive() {
				if (!this.token) {
					setTimeout(() => {
						this.$utils.judgeToken()
					}, 500)
					uni.$u.toast('未登录请先登录')
					return
				}
				this.$utils.navigateTo({
					url: '/Active/add?id=' + this.conquer_id + '&user_id=' + this.user_id
				})
			},
			monthChange(e) {
				this.$api.Conquer.Date.List(this.conquer_id, {
					date: e,
					user_id:this.user_id
				}).then(res => {
					this.markDays = res.data.dates
				})
			},
			getTimeDifferenceInDays(timestamp1, timestamp2) {
				// 将时间戳转换为日期对象
				const date1 = new Date(timestamp1);
				const date2 = new Date(timestamp2);

				// 计算两个日期之间的毫秒差
				const timeDifferenceInMilliseconds = Math.abs(date2 - date1);

				// 将毫秒转换为天数，一天有 24 * 60 * 60 * 1000 毫秒
				const oneDayInMilliseconds = 24 * 60 * 60 * 1000;
				const differenceInDays = Math.ceil(timeDifferenceInMilliseconds / oneDayInMilliseconds);

				return differenceInDays - 1;
			},
			onDayClick(data) {
				if (data == '未来日期不可选') return
				let date = data.date
				this.date = date.split('-').join('/')
				this.$refs.paging.reload()
			},
			change(e) {
				this.open(e ? 7 : 30)
			},
			close() {
				this.show = false
				this.chartData = null
			},
			open(days) {
				this.show = true
				uni.showLoading({
					title: '加载中...'
				})
				this.$api.User.Trend(this.user_id, this.conquer_id, {
					days: days
				}).then(res => {
					const fragments = res.data.fragments
					let categories = [],
						data = []
					for (let i in fragments) {
						categories.push(i)
						data.push(fragments[i].weight)
					}

					this.chartData = {
						categories: categories,
						series: [{
							name: '体重/单位Kg',
							data: data
						}]
					}
					uni.hideLoading()
				}).catch(err => {
					uni.hideLoading()
				})
			},
			formatFun(item) {
				let date = new Date(item);
				let options = {
					month: 'long',
					day: 'numeric'
				};
				let formattedDate = date.toLocaleString('default', options);
				return formattedDate
			},
			changeimage() {
				uni.chooseImage({
					count: 1,
					success: (res) => {
						const isLt3M = res.tempFiles[0].size / 1024 / 1024 < 3;
						console.log(res.tempFiles[0].size, isLt3M)
						if (!isLt3M) {
							uni.$u.toast('上传图片大小不能超过 3MB!');
						}
						res.tempFilePaths.forEach((item, index) => {
							this.conquer.cover = item
							uni.uploadFile({
								url: this.$config.url +
									'/api/my/conquer/bg/upload', //仅为示例，非真实的接口地址
								filePath: item,
								name: 'file',
								formData: {
									'conquer_id': this.conquer_id
								},
								header: {
									'Content-Type': 'application/json;charset=UTF-8',
									'Authorization': "Bearer " + uni.getStorageSync('token')
								},
							});
						})

					},
					fail: () => {

					}
				})
			},
			Followed() {
				if (!this.token) {
					setTimeout(() => {
						this.$utils.judgeToken()
					}, 500)
					uni.$u.toast('未登录请先登录')
					return
				}
				if (this.isFollowed) {
					uni.$u.toast('取消关注')
					this.$api.Followed.DelFollow({
						user_id: this.user_id
					}).then(res => {}).catch(err => {
						uni.$u.toast(err.data.message)
						this.isFollowed = !this.isFollowed
					})
				} else {
					uni.$u.toast('关注成功')
					this.$api.Followed.Follow({
						user_id: this.user_id
					}).then(res => {}).catch(err => {
						uni.$u.toast(err.data.message)
						this.isFollowed = !this.isFollowed
					})
				}
				this.isFollowed = !this.isFollowed

			},
			jumpImage() {
				this.$utils.navigateTo({
					url: '/User/images?id=' + this.user_id + '&conquer_id=' + this.conquer_id
				})
			},

			maxDatefun() {
				// 创建一个表示当前时间的Date对象
				var today = new Date();

				// 使用getDate()方法获取当前日期，并加上1得到明天的日期
				var tomorrowDate = today.getDate();

				// 使用setDate()方法设置Date对象的日期为明天的日期
				today.setDate(tomorrowDate);

				// 获取明天的年份、月份和日期
				var tomorrowYear = today.getFullYear();
				var tomorrowMonth = today.getMonth() + 1; // 月份从0开始，所以要加1
				var tomorrowDay = today.getDate();


				return tomorrowYear + "-" + tomorrowMonth + "-" + tomorrowDay
			},
			minDate() {
				// 获取当前时间
				var currentDate = new Date();

				// 获取一个月前的时间
				currentDate.setMonth(currentDate.getMonth() - 1);

				// 获取年、月、日
				var year = currentDate.getFullYear();
				var month = currentDate.getMonth() + 1; // 月份从0开始，需要加1
				var day = currentDate.getDate();

				// 格式化输出
				var formattedDate = year + "-" + month + "-" + day;
				return formattedDate
			},
			confirm(e) {
				let date = e[0]
				this.date = date.split('-').join('/')
				this.$refs.paging.reload()
				this.calendarShow = false
			},
			getDateil() {
				uni.showLoading({
					title: '加载中...'
				})
				this.$api.User.Conquer(this.user_id, this.conquer_id).then(res => {
					this.conquer = res.data.conquer
					this.user = res.data.conquer.user
					this.isFollowed = res.data.isFollowed
					this.isPublishedToday = res.data.isPublishedToday
					this.loading = false
					this.query(1, 10)
				}).catch(err => {
					uni.hideLoading()
				})

			},
			scroll(e) {
				const top = e.detail.scrollTop
				this.scrollTop = top * 2
				let index = 0
				let domTop0 = 0
				const query = uni.createSelectorQuery().in(this.$refs.active);
				query.selectAll('.activeBox').boundingClientRect(data => {
					data.forEach((rect, domIndex) => {
						let domTop = rect.top + top
						if (domIndex == 0) {
							domTop0 = domTop
						}
						if (top > (domTop - domTop0)) {
							index = domIndex
						}
						if (domIndex == data.length - 1) {
							this.playIndex = index

						}
					});
				}).exec();
			},
			query(page, size) {
				let obj = {
					page,
					size
				}
				if (this.date) {
					obj.date = this.date
				}
				console.log(obj)
				uni.showLoading({
					title: '加载中...'
				})
				this.$api.User.Active(this.user_id, this.conquer_id, obj).then(res => {
					this.Listloading = false
					this.$refs.paging.complete(res.data.fragments.data.map(item => {
						return {
							...item,
							user: this.user
						}
					}))
					uni.hideLoading()
				}).catch(err => {
					uni.hideLoading()
				})


			}

		}
	}
</script>

<style lang="scss" scoped>
	.access {
		display: flex;
		flex-direction: column;
		align-items: center;
		font-size: 26rpx;
		margin-right: 20rpx;
		text-align: center;
		margin-top: 20rpx;
	}

	.InfoBox {
		margin: 20rpx auto;
		background-color: #fff;
		box-shadow: 0 0 10rpx #ddd;
		padding: 10rpx;
		border-radius: 8rpx;

		.title {
			width: 100%;
			border-bottom: 1rpx solid #ddd;
			margin: 0 0 20rpx;
		}

		.infoContent {
			display: flex;
			width: 100%;
			justify-content: space-between;
		}
	}

	.selectSwitchBox {
		margin: 20rpx auto;
	}

	.calendar {
		position: absolute !important;
		left: 40rpx;
		bottom: 40rpx;
		z-index: 11;
		padding: 10rpx 20rpx !important;
	}

	.page {
		height: 100vh;
		padding-bottom: calc(constant(safe-area-inset-bottom) + 10rpx);
		/* 兼容 iOS 设备 */
		padding-bottom: calc(env(safe-area-inset-bottom) + 10rpx);
		box-sizing: border-box;
		background-color: #f5f5f5;
		display: flex;
		flex-direction: column;
	}

	.stepsBox {
		padding: 0rpx 20rpx;
		height: 100rpx;
		position: absolute;
		z-index: 1;
		display: flex;
		overflow: auto;
	}

	.fff {
		background-color: #f5f5f5;
		width: 100%;
		z-index: 111;
	}

	.radius {
		border-radius: 32rpx 32rpx 0 0;
		background-color: #f5f5f5;
		height: 20rpx;
		position: absolute;
		bottom: 0;
		width: 100vw;

	}

	.contentBox {
		padding: 20rpx 0 0 0;
		flex: 1;
		position: relative;
	}

	.background {
		height: 500rpx;
		width: 100%;
		position: relative;
	}

	.masking {
		background: linear-gradient(to top, rgba(0, 0, 0, 0.3), rgba(255, 255, 255, 0), rgba(255, 255, 255, 0), rgba(255, 255, 255, 0), rgba(255, 255, 255, 0));
		position: absolute;
		width: 100%;
		height: 500rpx;
		z-index: 2;
	}

	.backBox {
		position: fixed;
		left: 40rpx;
		z-index: 1111111111;
	}

	.Vr {
		background: rgba(0, 0, 0, 0.3);
		padding: 10rpx 20rpx;
		border-radius: 100rpx;
		color: #fff;
		position: relative;
		display: flex;
		align-items: center;
		justify-content: center;

		>button {
			opacity: 0;
			position: absolute;
			z-index: 1;
			width: 100%;
			height: 100%;
			top: 0;
			left: 0;
		}
	}



	.iconfont {
		margin-right: 10rpx;
	}

	.userBox {
		display: flex;
		position: absolute;
		width: 90vw;
		left: 40rpx;
		z-index: 111;
	}

	.radius {
		position: absolute;
		bottom: 0;
		height: 20rpx;
		width: 100vw;
		background-color: #f5f5f5;
		border-radius: 16rpx 16rpx 0 0;
		z-index: 11;
	}


	.access {
		display: flex;
		flex-direction: column;
		align-items: center;
		font-size: 26rpx;
		text-align: center;
		margin-top: 20rpx;
		margin-right: 10rpx;
	}

	.iconBox {
		border-radius: 100rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		padding: 8rpx;
	}

	.VrBox {
		display: flex;
		position: absolute;
		align-items: center;
		z-index: 111;

		>view {
			margin-right: 10rpx;
		}
	}

	.bottom {
		position: fixed;
		bottom: 10vh;
		right: 5vw;
		z-index: 1;

		>view {
			margin-top: 20rpx;
			width: 80rpx;
			height: 80rpx;
			font-size: 60rpx;
			background-color: #999;
			border-radius: 16rpx 16rpx 0 0;
			z-index: 11;
			display: flex;
			align-items: center;
			justify-content: center;
			border-radius: 100%;
		}

		.iconfont {
			color: #fff;
			margin: auto;
			font-size: 60rpx;
		}
	}

</style>